from fastapi import HTTPException
from ..dependencies import success, router, me, depens, User
from ..models.item import Cate, ItemComment
from ..models.user import History, Favorite
from ..models.base import Item
import math
from pydantic import BaseModel, Field

class ItemForm(BaseModel):
    name: str = Field(title="名称", default='', max_length=20)
    price: int = Field(title="价格", default=0, le=0)
    thumb: str = Field(title="缩略图", default='', max_length=20)
    detail: str = Field(title="详情", default='', max_length=100)

@router.get('/item', tags=['item'], dependencies=depens(False))
async def index(page: int = 1, size: int = 10):
    list = [row for row in Item.select().order_by(Item.id.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': Item.select().count()
    })
@router.get('/item/{id}', tags=['item'], dependencies=depens(False))
async def read(id: int):
    model = Item.get(Item.id == id)
    if me('id') != None:
        History.create(user_id=me('id'), item_id=id, thumb=model.thumb, price=model.price, name=model.name)
        favorited = Favorite.select().where(Favorite.item_id==id, Favorite.user_id==me('id')).exists()
    else:
        favorited = False
    comments = [row for row in ItemComment.select(ItemComment.content, ItemComment.user_id, User.nickname, User.avatar, ItemComment.create_at).join(User).where(ItemComment.item_id==id).paginate(1, 3).dicts()]
    return success({'favorited': favorited, 'comments': comments, **model.__data__})
### 创建
@router.post('/shop', tags=['item'], dependencies=depens())
async def save(post: ItemForm):
    model = Item.create(post)
    return success(model.__data__)
### 更新
@router.put('/shop/{id}', tags=['item'], dependencies=depens())
async def update(id: int, params):
    model = Item.update(params).where(Item.id==id).execute()
    return success(model.__data__)

#################
##### 分类 ######
#################
@router.get('/cate', tags=['item'], dependencies=depens(False))
async def tree():
    list = [[], {}, {}]
    for row in Cate.select().dicts():
        if row['id'] % 10000 == 0:
            list[0].append(row)
        elif row['id'] % 100 == 0:
            pid = math.floor(row['id'] / 10000) * 10000
            if(pid in list[1]):
                list[1][pid][row['id']] = row
            else:
               list[1][pid] = {}
        else:
            pid = math.floor(row['id'] / 100) * 100
            if(pid in list[2]):
                list[2][pid][row['id']] = row
            else:
               list[2][pid] = {}

    return success({'list': list, 'index': 110000})

@router.get('/cate/{id}', tags=['item'], dependencies=depens(False))
async def read(id: int):
    model = Cate.get(Cate.id == id)
    if model == None:
        raise HTTPException(status_code=404, detail="Address not found")
    return success({'form': model.__data__})
